from rest_framework import serializers

from apps.users.models import User


class UserListViewSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ("id", "username", "mobile", "email")


class UserAddListViewSerializer(serializers.ModelSerializer):
    # 密码二次校验 新增序化字段 password2
    password2 = serializers.CharField(write_only=True)

    class Meta:
        model = User
        # 新增的序化字段必须添加到序化字段中
        fields = ("username", "password", "mobile", "email", "password2")
    # 添加字段的额外参数 密码字段仅作序化使用
        extra_kwargs = {
            "password": {"write_only": True}
        }

    # 由于passwor2 的加入 自定义校验方法
    def validate(self, attrs):
        if attrs.get("password") != attrs.get("password2"):
            raise serializers.ValidationError("两次密码输入不一致")
        return attrs

    # 序化器自带创建方法不满足需求 进行重写
    def create(self, validated_data):
        # 由于模型中没有 password2 字段 所以在创建的时候需要删除
        del validated_data["password2"]
        user = User.objects.create_user(**validated_data)
        return user

